package megalopolis.server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import megalopolis.common.Config;
import megalopolis.model.Building;
import megalopolis.model.Man;

/**
 * User: Kirill
 * Date: 19.02.2008
 */
public class Server {

	public void start() throws ServerException {
		// load config
		Config config = getConfig();

		// load model
		World world = getWorld(config.getString("world.file"));

		// create network thread
		NetworkThread network = new NetworkThread();

		// create engine thread
		EngineThread engine = new EngineThread(world, network);

		ListenerThread listener = new ListenerThread(config.getInt("listener.port"), network);
		
		engine.start();
		network.start();
		listener.start();
	}

	public World getWorld(String worldFile) {
		ObjectInputStream in = null;
		World world;
		try {
			in = new ObjectInputStream(new FileInputStream(worldFile));
			world = (World) in.readObject();
		} catch (Exception e) {
			world = createDemoWorld();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// do nothing
				}
			}
		}
		return world;
	}

	private World createDemoWorld() {
		World world = new World();

		Building building = new Building();
		building.width = 10;
		building.height = 5;
		building.x = 10;
		building.y = 15;
		world.buildings.add(building);

		building = new Building();
		building.width = 10;
		building.height = 25;
		building.x = -30;
		building.y = 0;
		world.buildings.add(building);

		Man man = new Man();
		man.x = -5;
		man.y = -10;
		man.name = "Test man";
		world.mans.add(man);

		return world;
	}

	public Config getConfig() throws ServerException {
		try {
			return new Config("server.properties");
		} catch (IOException e) {
			throw new ServerException("Can't load config file");
		}
	}
}
